from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
from rest_framework_jwt.serializers import jwt_decode_handler,jwt_get_username_from_payload
import jwt
from user import models

'''用户认证模块，校验用户是否登录了。有些接口是需要登录的用户才能访问。'''

class MyJWTAuthentication(BaseAuthentication):
    def authenticate(self, request):
        token = request.META.get('HTTP_AUTHORIZATION')
        if token:
            #jwt通过了通过三段tokken，取出payload的方法，并且有校验功能
            try:
                payload = jwt_decode_handler(token)
                username = payload.get('username')
                user = models.User.objects.get(id=payload.get('user_id'))
                role = user.role
                return (username,{'token':token,'id':payload.get('user_id'),'role':role})
            except jwt.ExpiredSignature:
                msg = {'code':104,'msg':'token过期'}
                raise AuthenticationFailed(msg)
            except jwt.DecodeError:
                msg= {'code':104,'msg':'token非法'}
                raise AuthenticationFailed(msg)
            except jwt.InvalidTokenError:
                msg={'code':104,'msg':'非法用户'}
                raise AuthenticationFailed(msg)
            except Exception as e:
                msg=str(e)
                raise AuthenticationFailed(msg)
        raise AuthenticationFailed({'code':104,'msg':'请求方式错误，请携带token'})